﻿using GDGeek;
using MrPP.Common;
using MrPP.iot;
using MrPP.ProgramPlatform;
using MrPP.Restful;
using MrPP.SocketSystem;
using MrPP.Tracking;
using MrPP.Helper;
using MrPP.UX;
using System;
using System.Collections.Generic;
using UnityEngine;
using Heartbeat = MrPP.Restful.Heartbeat;
using MrPP.Myth;
using System.Text.RegularExpressions;

namespace MrPP.SerriedCabinet
{
    public class ResultData {
        public long time;
        public bool succeed;
    }
    public class WindowProcess : GDGeek.Singleton<WindowProcess>, IBridgeReceiver
    {


      //  [SerializeField]
       // SetAsgardPose _anchor = null;
      //  private AsgardPoseData pose_ = null;



        [SerializeField]
        WindowFactory _factory;
        // [SerializeField]
        // private VuforiaMark.Mark _mark = VuforiaMark.Mark.Mark8;


        //  [SerializeField]
        //  private Transform _anchor;
#if UNITY_EDITOR

        [SerializeField]
        private string _stateName;
#endif
        [SerializeField]
        private WindowModel _manager;//服务器模型

        private FSM fsm_ = new FSM();


        //接收数据
        public void onInitialStatus(InitialStatusFactory.Data data)
        {
            this.fsm_.post("InitialStatus");
        }

        internal void doOpen(int id)
        {

         //   openId_ = item2;
            fsm_.post("open_id", id);
        }

        /*
public void onAreaColumnConfiguration(AreaColumnConfigurationFactory.Data data)
{
   this.fsm_.post("AreaColumnConfiguration");
}*/
        /*
        public void testScanning()
        {
            StartWindow.Data data = new StartWindow.Data();
            data.url = "http://localhost:3000/geek/1/1";

            url_ = data.url;
            anchor_ = this._anchor;
            BoxRoot.Instance.mount(anchor_);
            this.fsm_.post("scanning");
        }*/

      
        public void OnDestory()
        {

            BridgeBroadcast.Instance.removeReceiver(this);
        }
        void Start()
        {

            BridgeBroadcast.Instance.addReceiver(this);

            InitialStatusFactory.Instance.onRecevie += onInitialStatus;


            fsm_.addState("wait", wait());

            fsm_.addState("start", start());
            fsm_.addState("init", init(), "start");//创建窗口
          //  fsm_.addState("scanning", scanning(), "start");//等待扫描
            fsm_.addState("setup", setup(), "start");//链接并得到setup数据
            fsm_.addState("initialStatus", initialStatus(), "start");//



            fsm_.addState("main", main());
         
            fsm_.init("wait");
         
        }

        private string url_;
     //   private Transform anchor_ = null;
        public void doQRCode(string url)
        {

            Regex rgx = new Regex(@"^(http[s]?://[^/]+/)(.+)$");
            Match match = rgx.Match(url);
            if (!match.Success) {
                return;
            }
          


            url_ = url;
            fsm_.post("scanning");
        }
      /*  public void doVuforia(Transform anchor)
        {
            anchor_ = anchor;
            fsm_.post("scanning");
        }*/
        public void doStart() {
            fsm_.post("start");
        }
       
        public void doVentilate()
        {
            fsm_.post("ventilate");
        }

        public void doStop()
        {
            fsm_.post("stop");
        }
        public void doClose()
        {

            fsm_.post("close");
        }
        public void doOpen()
        {
            fsm_.post("open");
        }
       
        public void doSelect(int id)
        {
            Debug.Log(id);
            if (id == CabinetGroup.Instance.data.cabinets.fix)
            {
                return;
            }
            if (id >= CabinetGroup.Instance.count || id < 0)
            {
                return;
            }
          //  selected_ = id;
            fsm_.post("select", id);
        }
        private StateBase wait()
        {
            State state = new State();
            state.addAction("start", "init");
            return state;
        }
        /*
        private int openId_ = -1;
        private StateBase open_id()
        {
            State ts = TaskState.Create(delegate {
                return BoxOperation.Instance.open(openId_);
            }, this.fsm_, "run");
            return ts;
        }
        
        private StateBase open()
        {

            State ts = TaskState.Create(delegate {

                return BoxOperation.Instance.open(selected_);


            }, this.fsm_, "run");
            return ts;

        }
        */
        private StateBase start()
        {
            State state = new State();
            state.onStart += delegate
            {
                _manager.state = WindowModel.State.Start;
          
            };
            state.onOver += delegate
            {

            };
            return state;
        }
        /*
        private StateBase init()
        {
            State state = TaskState.Create(delegate {
                _factory.create();
                Task task = new Task();
                return task;
            }, fsm_, "scanning");
            return state;
        }
        */
        private StateBase init()
        {
            State state = new State();
            state.onStart += delegate
            {
                _factory.create();
            };
            state.addAction("scanning", delegate
            {
                if (!string.IsNullOrEmpty(url_)/* && anchor_ != null*/)
                {
                    return "setup";
                }
                return "";
            });
            state.onOver += delegate
            {
                UriManager.GetOrCreateInstance.getUri("api").value = url_;
            };
            return state;
        }

        private StateBase setup()
        {
            State state = TaskState.Create(delegate {
                var op = Restful.RestfulManager.Instance.options(Restful.RestfulManager.Uri(UriManager.GetOrCreateInstance.getUri("api").value, "setup"));
                Task task = Restful.RestfulManager.Instance.getTask<Setup.Data>(op, delegate (Setup.Data data)
                {
                    Heartbeat.Instance.open();
                    CabinetGroup.Instance.data = data;
                });


                return task;
            }, fsm_, "initialStatus");

            state.onStart += delegate
            {
                var op = Restful.RestfulManager.Instance.options(Restful.RestfulManager.Uri(UriManager.GetOrCreateInstance.getUri("api").value, "areaColumnConfiguration"));
                Restful.RestfulManager.Instance.get<ResultData>(op, delegate (ResultData result)
                {
                    Debug.Log(result);
                });

            };
            return state;

        }
       
        private StateBase initialStatus()
        {
            State state = new State();
            state.onStart += delegate
            {
                var op = Restful.RestfulManager.Instance.options(Restful.RestfulManager.Uri(UriManager.GetOrCreateInstance.getUri("api").value, "initialStatus"));
                Restful.RestfulManager.Instance.get<ResultData>(op, delegate (ResultData result)
                {
                    Debug.Log(result.time);
                });

            };
            state.addAction("InitialStatus", "main");
            return state;
        }


        private StateBase main()
        {

            State state = new State();
            state.onStart += delegate
            {
                _manager.state = WindowModel.State.Main;
            };

            state.addAction("select", delegate(FSMEvent evt) {
                _manager.selected = (int)evt.obj;
            });


            state.addAction("stop", delegate {
                TaskManager.Run(BoxOperation.Instance.stop());
                _manager.selected = -1;
            });
            state.addAction("close", delegate {
                TaskManager.Run(BoxOperation.Instance.close());
                _manager.selected = -1;
            });
            state.addAction("open", delegate {
                TaskManager.Run(BoxOperation.Instance.open(_manager.selected));
                _manager.selected = -1;
            });
            state.addAction("open_id", delegate(FSMEvent evt) {
                TaskManager.Run(BoxOperation.Instance.open((int)evt.obj));
                _manager.selected = -1;
            });
            state.addAction("ventilate", delegate (FSMEvent evt) {
                TaskManager.Run(BoxOperation.Instance.ventilate());
                _manager.selected = -1;
            });


            state.onOver += delegate
            {

             
            };
            return state;
         
        }

      

       

      /*
        private StateBase run()
        {
            State state = new State();
            state.onStart += delegate
            {
                _manager.state = WindowModel.State.Main;
             
            };

            state.addAction("select", "selected");
            state.addAction("stop", "stop");
            state.addAction("close", "close");
            state.addAction("open", "open");
            state.addAction("open_id", "open_id");
            state.addAction("ventilate", "ventilate");

            return state;  
        }
        */
     
      
     
       

        /*

        private StateBase stop()
        {

            State ts = TaskState.Create(delegate {
                return BoxOperation.Instance.stop();

            }, this.fsm_, "run");
            return ts;
        }
      
                private StateBase open()
                {

                    State ts = TaskState.Create(delegate {

                        return BoxOperation.Instance.open(selected_);


                    }, this.fsm_, "run");
                    return ts;

                }
                */
        /*
        private StateBase close()
        {
            State ts = TaskState.Create(delegate {
                return BoxOperation.Instance.close();
  
            }, this.fsm_, "run");
            return ts;
        }
        private StateBase ventilate()
        {
            State ts = TaskState.Create(delegate {
                return BoxOperation.Instance.ventilate();
            }, this.fsm_, "run");
            return ts;
        }

        RespTheInitialStatus.Data _status;

        
        private StateBase input()
        {
            State state = new State();
            state.onStart += delegate
            {

                _manager.state = WindowModel.State.Start;
              
            };
            state.onOver += delegate
            {
            };
            return state;
        }
        RespAreaColumnConfiguration.Data _setup;

      
          private StateBase selected()
          {
              State state = new State();
              state.onStart += delegate
              {
                  _manager.selected = selected_;
              };


              state.addAction("select", "selected");
              state.addAction("close", "close");
              state.addAction("ventilate", "ventilate");
              state.addAction("open", "open");
              state.addAction("stop", "stop");

              state.onOver += delegate
              {

                  //button.state = Button.State.Enabled;
                  //button.refresh();

                  _manager.selected = -1;
                  //_manager._operation.gameObject.SetActive(false);
              };
              return state;
          }

          private int selected_ = -1;
          */
        public string handle => this.gameObject.longName();

        private Dictionary<string, Action<object>> evtMap_ = new Dictionary<string, Action<object>>();
        void Awake() {
            /* evtMap_.Add("anchor", delegate (object value)
             {
                 AsgardPoseData data = (AsgardPoseData)value;
                 if (pose_ == null)
                 {
                     _anchor._pose = data.aPose;
                     this.doVuforia(_anchor.transform);
                 }
                 pose_ = data;
             });

             evtMap_.Add("touch", delegate (object value)
             {
                 if (pose_ != null)
                 {
                     _anchor._pose = pose_.aPose;
                 }
             });
             */
            evtMap_.Add("qrcode", delegate (object value)
            {
                this.doQRCode((string)value);
            });
            evtMap_.Add("start", delegate (object value)
            {
                this.doStart();
            });
            evtMap_.Add("close", delegate (object value)
            {
                this.doClose();
            });
            evtMap_.Add("ventilate", delegate (object value)
            {
                this.doVentilate();
            });
            evtMap_.Add("stop", delegate (object value)
            {
                this.doStop();
            });
            evtMap_.Add("open", delegate (object value)
            {
                this.doOpen();
            });
            evtMap_.Add("open_id", delegate (object value)
            {
                this.doOpen((int)(value));
            });
            evtMap_.Add("select", delegate (object value) {
                this.doSelect((int)value);
            });
           
        }
        public void broadcast(string evt, object value)
        {
            if (evtMap_.ContainsKey(evt)) {
                evtMap_[evt](value);
            }
            Debug.Log("message:" + evt);
            
            
            /*if (evt == "anchor")
            {
               
            }
            else if (evt == "touch")
            {
                if (pose_ != null)
                {
                    _anchor._pose = pose_.aPose;
                }
            }
            else if (evt == "qrcode")
            {
                this.doQrcode((string)value);
            }
            else if (evt == "close")
            {
                this.doClose();
            }
            else if (evt == "ventilate")
            {
                this.doVentilate();
            }
            else if (evt == "stop")
            {
                this.doStop();
            }
            else if (evt == "open")
            {
                this.doOpen();
            }
            else if (evt == "open_id")
            {
                 this.doOpen((int)value);
            }
            else if (evt == "select")
            {
                this.doSelect((int)value);
            }
           */
        }

#if UNITY_EDITOR
        void Update() {
            _stateName = fsm_.getCurrSubState().name;
        }

     
#endif


    }
}